﻿using Dln.Common;
using Dln.Common.Helper;
using Dln.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// BasePage 的摘要说明
/// </summary>
public class BasePage : System.Web.UI.Page
{
    protected string AppId = CommonHelper.GetAppSettings("AppID");
    protected string AppSecret = CommonHelper.GetAppSettings("AppSecret");


    public string GetAuthOpenId()
    {
        string code = DNTRequest.GetString("CODE");
        string strOpenId = "";

        if (!String.IsNullOrEmpty(code) && code != "authdeny")
        {
            string json = RequestHelper.SendGet(String.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, AppSecret, code));
            if (!String.IsNullOrEmpty(json))
            {
                try
                {
                    OAuthConfig oAuthConfig = JSONHelper.FromJson<OAuthConfig>(json);
                    if (oAuthConfig != null)
                    {
                        setLoginCookieOpenId(oAuthConfig.openid);
                        strOpenId = oAuthConfig.openid;
                        //return oAuthConfig.openid;
                    }
                    else
                    {
                        ResponseToPage("请先关注公众账号，且从微信客户端访问");
                    }
                }
                catch (Exception ex)
                {
                    ResponseToPage("请先关注公众账号，且从微信客户端访问");
                }
            }
        }
        else
        {

            HttpCookie userCookies = HttpContext.Current.Request.Cookies["CookiesOpenid"];
            if (userCookies != null && !String.IsNullOrEmpty(userCookies.ToString()))
            {
                strOpenId = userCookies["OpenId"] == null ? "" : userCookies["OpenId"].ToString();
            }
            else
            {
                string strUrl = Request.RawUrl.ToString();
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}%2fpage%2fCommon%2fWeixinRequestPage.aspx%3ffrom%3d{2}&response_type=code&scope=snsapi_userinfo&state=membercenter#wechat_redirect ", AppId, Server.UrlEncode(CommonHelper.GetAppSettings("mainurl")), Server.UrlEncode(strUrl));
                Response.Redirect(url);
            }
        }
        return strOpenId;
    }

    public void ResponseToPage(string message)
    {
        Response.Redirect(String.Format("/page/Common/message.aspx?m={0}", Server.UrlEncode(message)));
        //Response.Redirect(" http://www.syzyyy.cn/");
    }

    /// <summary>
    /// 设置登陆cookie
    /// </summary>
    public static void setLoginCookieOpenId(string openid)
    {
        HttpCookie userCookie = HttpContext.Current.Request.Cookies["CookiesOpenid"];
        if (userCookie != null)
        {
            HttpContext.Current.Response.Cookies.Remove("CookiesOpenid");
        }
        userCookie = new HttpCookie("CookiesOpenid");
        userCookie.Values["OpenId"] = openid;
        userCookie.Expires = DateTime.Now.AddDays(1);
        HttpContext.Current.Response.AppendCookie(userCookie);
    }

    /// <summary>
    /// 页面异常
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Error(object sender, EventArgs e)
    {
        string errorMsg = String.Empty;
        Exception currentError = Server.GetLastError();
        Exception iex = currentError.InnerException;
        string message = String.Empty;
        string stackTrace = String.Empty;
        if (iex != null)
        {
            message = iex.Message;
            stackTrace = iex.StackTrace;
        }
        Server.ClearError();
        Response.Redirect(String.Format("/page/Common/message.aspx?m=" + message));
        //Response.Redirect(" http://www.syzyyy.cn/");
    }
}